using System;
using System.Web;
using System.IO;
using Jalal.Library.Utility;
using Jalal.Library.Data;
using BCGC.DAL;
using System.Configuration;
using System.Collections.Generic;
using Jalal.Library.DataStructure;
using System.Data;
using System.Data.SqlTypes;

namespace BCGC.BLL.BusinessObject.Resource
{

    public class Crack : ResourceBase
    {
        private int crackId;
        public int CrackId
        {
            get { return crackId; }
        }

        private String fileUrl;
        public String FileUrl
        {
            get
            {
                return fileUrl;
            }
            set
            {
                fileUrl = value;
            }
        }

        public Crack()
        {
            this.crackId = 0;
            this.fileUrl = string.Empty;
            this.createDateTime = SqlDateTime.MinValue.Value;
            this.description = string.Empty;
            this.relatedGame = null;
            this.title = string.Empty;
            this.isActive = false;
            this.totalView = 0;
            this.rating = 0;
            this.totalRatingVote = 0;
        }

        public Crack(DataRow dataRow, bool fullLoad)
        {
            if (dataRow != null)
            {
                if (dataRow.Table.Columns.Contains("CrackId"))
                    this.crackId = (int)CommonUtility.FilterNull(dataRow["CrackId"], typeof(int));
                if (dataRow.Table.Columns.Contains("FileUrl"))
                    this.fileUrl = (string)CommonUtility.FilterNull(dataRow["FileUrl"], typeof(string));
                if (dataRow.Table.Columns.Contains("CreateDateTime"))
                    this.createDateTime = (DateTime)CommonUtility.FilterNull(dataRow["CreateDateTime"], typeof(DateTime));
                if (dataRow.Table.Columns.Contains("Description"))
                    this.description = (string)CommonUtility.FilterNull(dataRow["Description"], typeof(string));
                if (dataRow.Table.Columns.Contains("Title"))
                    this.title = (string)CommonUtility.FilterNull(dataRow["Title"], typeof(string));
                if (dataRow.Table.Columns.Contains("IsActive"))
                    this.isActive = (bool)CommonUtility.FilterNull(dataRow["IsActive"], typeof(bool));
                if (dataRow.Table.Columns.Contains("TotalView"))
                    this.totalView = (int)CommonUtility.FilterNull(dataRow["TotalView"], typeof(int));
                if (dataRow.Table.Columns.Contains("Rating"))
                    this.rating = (int)CommonUtility.FilterNull(dataRow["Rating"], typeof(int));
                if (dataRow.Table.Columns.Contains("TotalRatingVote"))
                    this.totalRatingVote = (int)CommonUtility.FilterNull(dataRow["TotalRatingVote"], typeof(int));

                if (fullLoad)
                    this.relatedGame = new Game(dataRow);
                else
                    this.relatedGame = null;
            }
            else
            {
                this.crackId = 0;
                this.fileUrl = string.Empty;
                this.createDateTime = SqlDateTime.MinValue.Value;
                this.description = string.Empty;
                this.relatedGame = null;
                this.title = string.Empty;
                this.isActive = false;
                this.totalView = 0;
                this.rating = 0;
                this.totalRatingVote = 0;
            }
        }

        private static ReadWriteCustomCollection<Crack> LoadFromDataTable(DataTable data)
        {
            ReadWriteCustomCollection<Crack> result = new ReadWriteCustomCollection<Crack>();

            if (data != null && data.Rows.Count > 0)
            {
                foreach (DataRow row in data.Rows)
                {
                    result.Add(new Crack(row, true));
                }
            }
            return result;
        }

        public static string UploadCrackFile(HttpPostedFile postedFile)
        {
            return FileAccessUtility.UploadFile(postedFile, ConfigurationSettings.AppSettings["FCKeditor:UserFilesPath"] 
                + "file/crack/", FileAccessUtility.FileTypes.Zip);
        }

        public static bool Create(string title, int gameId, string description, 
            string fileUrl, bool isActive)
        {
            DataFactory.GetDataMiner().BeginTransaction(true);
            int id = ResourceData.CreateNewCrack(title, gameId, description, fileUrl, isActive);
            DataFactory.GetDataMiner().CommitTransaction();

            return (id > 0);
        }

        public static void Delete(List<int> cracksToDelete)
        {
            DataFactory.GetDataMiner().BeginTransaction(true);
            DataTable crackFiles = ResourceData.GetCrackFileLocationsToForDelete(cracksToDelete);
            DataFactory.GetDataMiner().CommitTransaction();

            DataFactory.GetDataMiner().BeginTransaction(false);

            try
            {
                int deletedItemCount = ResourceData.DeleteCracks(cracksToDelete);
                if (deletedItemCount == cracksToDelete.Count)
                    DataFactory.GetDataMiner().CommitTransaction();
                else
                    throw new Exception("Failed to delete all items");

                if (crackFiles != null && crackFiles.Rows.Count > 0)
                {
                    foreach (DataRow row in crackFiles.Rows)
                    {
                        string fileUrl = (string)row["FileUrl"];
                        if(!string.IsNullOrEmpty(fileUrl))
                            FileAccessUtility.DeleteFile(fileUrl);
                    }
                }
            }
            catch (Exception ex)
            {
                DataFactory.GetDataMiner().RollBackTransaction();
                throw ex;
            }
        }

        public static void UpdateActive(List<int> activeCracks, List<int> inactiveCracks)
        {
            DataFactory.GetDataMiner().BeginTransaction(false);

            try
            {
                int updatedItemCount = ResourceData.UpdateActiveCrack(activeCracks,
                    inactiveCracks);
                if (updatedItemCount == activeCracks.Count + inactiveCracks.Count)
                    DataFactory.GetDataMiner().CommitTransaction();
                else
                    throw new Exception("Failed to update all items");
            }
            catch (Exception ex)
            {
                DataFactory.GetDataMiner().RollBackTransaction();
                throw ex;
            }
        }

        public static ReadWriteCustomCollection<Crack> GetAllCracks(int currentPageIndex,
            string sortOrder, int pageSize, string title, string gameTitle, DateTime? createDateFrom,
            DateTime? createDateTo, bool? isActive, out int totalData)
        {
            DataFactory.GetDataMiner().BeginTransaction(true);

            totalData = 0;

            DataTable crackData = ResourceData.GetAllCracks(currentPageIndex, sortOrder, pageSize, 
                title, gameTitle, createDateFrom, createDateTo, isActive, out totalData);
            ReadWriteCustomCollection<Crack> cracks = LoadFromDataTable(crackData);

            DataFactory.GetDataMiner().CommitTransaction();

            return cracks;
        }

        public static Crack GetCrackById(int id)
        {
            DataFactory.GetDataMiner().BeginTransaction(true);
            Crack crack = null;
            DataTable data = ResourceData.GetCrackById(id);
            if (data != null && data.Rows.Count > 0)
                crack = new Crack(data.Rows[0], true);

            DataFactory.GetDataMiner().CommitTransaction();

            return crack;
        }

        public static bool Update(int id, string title, int gameId, string description, 
            string fileUrl, bool isActive)
        {
            DataFactory.GetDataMiner().BeginTransaction(true);
            List<int> cracksToDelete = new List<int>();
            cracksToDelete.Add(id);
            DataTable crackFiles = ResourceData.GetCrackFileLocationsToForDelete(cracksToDelete);
            DataFactory.GetDataMiner().CommitTransaction();

            if (crackFiles != null && crackFiles.Rows.Count > 0)
            {
                foreach (DataRow row in crackFiles.Rows)
                {
                    string oldFileUrl = (string)row["FileUrl"];
                    if (!string.IsNullOrEmpty(oldFileUrl))
                        FileAccessUtility.DeleteFile(oldFileUrl);
                }
            }

            DataFactory.GetDataMiner().BeginTransaction(true);
            int updateCount = ResourceData.UpdateCrack(id, title, gameId, description, fileUrl,
                isActive);
            DataFactory.GetDataMiner().CommitTransaction();

            return (updateCount > 0);
        }

        public static ReadWriteCustomCollection<Crack> GetCrackByGame(int currentPageIndex, string sortOrder,
            int pageSize, string title, int gameId, out int totalData)
        {
            DataFactory.GetDataMiner().BeginTransaction(true);

            totalData = 0;

            DataTable crackData = ResourceData.GetCracksByGame(currentPageIndex, sortOrder, pageSize,
                title, gameId, out totalData);
            ReadWriteCustomCollection<Crack> cracks = LoadFromDataTable(crackData);

            DataFactory.GetDataMiner().CommitTransaction();

            return cracks;
        }
    }

}
